﻿using System;
class SortingArrayBinaryK
{
    static void Main()
    {
        int lenght;
        int compairingNum;
        int compairingNumNew;
        Console.Write("please enter the lenght of array: ");
        while (true)
        {
            try
            {
                lenght = int.Parse(Console.ReadLine());
                break;
            }
            catch (Exception)
            {
                Console.Write("Please re-enter lenght:");
            }
        }
        int[] theArray;
        theArray = new int[lenght];
        for (int i = 0; i < lenght; i++)
        {
            Console.Write("Please enter the {0} element of array: ", i);
            while (true)
            {
                try
                {
                    theArray[i] = int.Parse(Console.ReadLine());
                    break;
                }
                catch (Exception)
                {
                    Console.Write("Please re-enter element:");
                }
            }
        }
        Console.Write("please enter number K: ");
        while (true)
        {
            try
            {
                compairingNum = int.Parse(Console.ReadLine());
                break;
            }
            catch (Exception)
            {
                Console.Write("Please re-enter number: ");
            }
        }
        compairingNumNew = compairingNum;
        Array.Sort(theArray);
        int index;
        do
        {
            index = Array.BinarySearch(theArray, compairingNumNew);
            if (index < 0)
            {
                compairingNumNew--;
            }
            else
            {
                Console.WriteLine("the biggest element <=K is: {0}", compairingNumNew);
            }

        } while ((index < 0) && (compairingNumNew != 0));
        if (compairingNumNew == 0)
        {
            Console.WriteLine("there is no number <= {0}", compairingNum);
        }
        Console.ReadLine();
    }
}

